
import router from './router';
import store from './store';


//不需要登录的路径
const routers = ['/login', '/register']

//第一次访问 检查用户访问的正确性
router.beforeEach((to, from, next) => {
    //如果请求路径是根路径 则重定向到首页
    console.log(1);
    if (to.path === '') {
        next('/');
    }
    //如果请求路径是不需要登录的 直接放行
    if (routers.includes(to.path)) {
        next();
    } else {
        //如果请求路径是需要登录的 则验证token是否正确
        const token = store.getters['auth/getToken'];
        if (token===undefined || token === null) {
            next('/login');
        } else {
            //如果是登陆状态 根据用户信息获取权限
            //查看vuex是否有缓存了权限
            if(store.getters["permissions/getPermissions"].length === 0){
                store.dispatch('permissions/fetchPermissions').then((permissions) => {
                    let s = router.getRoutes();
                    next({ ...to, replace: true });
                }).catch((err) => {
                    alert(err);
                    next('/login');
                });
            } else {
                //如果有缓存 则直接放行
                next();
            }
        }
        //next();
    }
    const token = localStorage.getItem('token');

}

)